package com.lagou.edu.filter;

import com.lagou.edu.utils.UrlMatch;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.PostConstruct;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;

@Component
public class LoginFilter implements GlobalFilter {

    private Set<String> excludeUrls = new HashSet<>();

    @PostConstruct
    public void init() {
        excludeUrls.add("/api/user/register/**");
        excludeUrls.add("/api/user/isRegistered/**");
        excludeUrls.add("/api/user/login/**");
        excludeUrls.add("/api/code/**");
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        boolean match = UrlMatch.match(excludeUrls, exchange.getRequest().getPath().toString());
        if (match) {
            // 合法请求，放行，执行后续的过滤器
            return chain.filter(exchange);
        }

        ServerHttpResponse response = exchange.getResponse();
        String token = getToken(exchange);
        if (StringUtils.isEmpty(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            String data = "Unauthorized!";
            DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
            return response.writeWith(Mono.just(wrap));
        }
        // 合法请求，放行，执行后续的过滤器
        return chain.filter(exchange);
    }

    public String getToken(ServerWebExchange exchange) {
        MultiValueMap<String, HttpCookie> cookies = exchange.getRequest().getCookies();
        Optional<HttpCookie> optional = cookies.values().stream()
                .flatMap(List::stream).filter(httpCookie -> httpCookie.getName().equals("token"))
                .findAny();
        return optional.map(HttpCookie::getValue).orElse(null);
    }

}